<template>
  <!-- 主容器，loaded控制加载动画 -->
  <view class="register-container" :class="{ show: loaded }">
    <!-- 顶部波浪装饰 -->
    <view class="header-wave">
      <view class="wave-shape"></view>
    </view>
    
    <!-- 标题区域 -->
    <view class="title-section">
      <view class="title-wrapper">
        <view class="pulse-dot"></view> <!-- 脉冲动画圆点 -->
        <text class="main-title">创建账号</text>
      </view>
      <text class="subtitle">注册即可享受完整功能体验</text>
    </view>

    <!-- 注册表单容器 -->
    <view class="form-container">
      <!-- 邮箱输入组 -->
      <view class="input-group">
        <view class="floating-label-wrapper">
          <input 
            class="floating-input" 
            type="email"
            maxlength="100"
            v-model="email"
            :class="{ 'has-value': email }"
            @focus="focusField('email')"
            @blur="blurField('email')"
            @input="onEmailInput"
          />
          <!-- 浮动标签 -->
          <text class="floating-label" :class="{ 'focused': focusedField === 'email' || email }">
            邮箱号码
          </text>
          <!-- 输入框图标 -->
          <view class="input-icon">
            <text class="icon">📧</text>
          </view>
        </view>
      </view>

      <!-- 验证码输入组 -->
      <view class="input-group">
        <view class="verification-wrapper">
          <view class="floating-label-wrapper verification-input">
            <input 
              class="floating-input" 
              type="number"
              maxlength="6"
              v-model="verificationCode"
              :class="{ 'has-value': verificationCode }"
              @focus="focusField('code')"
              @blur="blurField('code')"
            />
            <text class="floating-label" :class="{ 'focused': focusedField === 'code' || verificationCode }">
              验证码
            </text>
            <view class="input-icon">
              <text class="icon">🔐</text>
            </view>
          </view>
          <!-- 验证码发送按钮 -->
          <button 
            class="code-btn" 
            :class="{ 'disabled': countdown > 0 || !isValidEmail }"
            @tap="sendCode"
            :disabled="countdown > 0 || !isValidEmail"
          >
            {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
          </button>
        </view>
      </view>

      <!-- 密码输入组 -->
      <view class="input-group">
        <view class="floating-label-wrapper">
          <input 
            class="floating-input" 
            :type="showPassword ? 'text' : 'password'"
            v-model="password"
            :class="{ 'has-value': password }"
            @focus="focusField('password')"
            @blur="blurField('password')"
          />
          <text class="floating-label" :class="{ 'focused': focusedField === 'password' || password }">
            设置密码
          </text>
          <view class="input-icon">
            <text class="icon">🔒</text>
          </view>
          <!-- 密码可见切换按钮 -->
          <view class="eye-icon" @tap="togglePassword">
            <text class="icon">{{ showPassword ? '👁️' : '👁️‍🗨️' }}</text>
          </view>
        </view>
        <!-- 密码强度指示器 -->
        <view class="password-strength" v-if="password">
          <view class="strength-bar">
            <view 
              class="strength-fill" 
              :class="passwordStrengthClass"
              :style="{ width: passwordStrengthWidth }"
            ></view>
          </view>
          <text class="strength-text" :class="passwordStrengthClass">
            {{ passwordStrengthText }}
          </text>
        </view>
      </view>

      <!-- 确认密码输入组 -->
      <view class="input-group">
        <view class="floating-label-wrapper">
          <input 
            class="floating-input" 
            :type="showConfirmPassword ? 'text' : 'password'"
            v-model="confirmPassword"
            :class="{ 'has-value': confirmPassword }"
            @focus="focusField('confirm')"
            @blur="blurField('confirm')"
          />
          <text class="floating-label" :class="{ 'focused': focusedField === 'confirm' || confirmPassword }">
            确认密码
          </text>
          <view class="input-icon">
            <text class="icon">🔑</text>
          </view>
          <view class="eye-icon" @tap="toggleConfirmPassword">
            <text class="icon">{{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}</text>
          </view>
        </view>
        <!-- 密码匹配提示 -->
        <view class="password-match" v-if="confirmPassword">
          <text class="match-text" :class="{ 'match': passwordsMatch, 'no-match': !passwordsMatch }">
            {{ passwordsMatch ? '✓ 密码匹配' : '✗ 密码不匹配' }}
          </text>
        </view>
      </view>

      <!-- 用户协议区域 -->
      <view class="agreement-section">
        <view class="checkbox-wrapper" @tap="toggleAgreement">
          <view class="custom-checkbox" :class="{ 'checked': agreedToTerms }">
            <text class="checkmark" v-if="agreedToTerms">✓</text>
          </view>
          <text class="agreement-text">
            我已阅读并同意
            <text class="link-text" @tap.stop="viewTerms">《用户协议》</text>
            和
            <text class="link-text" @tap.stop="viewPrivacy">《隐私政策》</text>
          </text>
        </view>
      </view>

      <!-- 注册按钮 -->
      <button 
        class="register-btn" 
        :class="{ 'disabled': !canRegister }"
        @tap="handleRegister"
        :disabled="!canRegister"
      >
        <text class="btn-text">立即注册</text>
        <view class="btn-loading" v-if="isRegistering">
          <text class="loading-text">⏳</text>
        </view>
      </button>

      <!-- 登录提示 -->
      <view class="login-hint">
        <text class="hint-text">已有账号？</text>
        <text class="login-link" @tap="goLogin">立即登录</text>
      </view>
    </view>
  </view>
</template>
<script>
import request from '@/api/request.js'

export default {
  data() {
    return {
      email: '', // 邮箱
      verificationCode: '', // 验证码
      password: '', // 密码
      confirmPassword: '', // 确认密码
      showPassword: false, // 是否显示密码
      showConfirmPassword: false, // 是否显示确认密码
      focusedField: '', // 当前聚焦的输入框
      agreedToTerms: false, // 是否同意协议
      countdown: 0, // 验证码倒计时
      isRegistering: false, // 是否正在注册
      loaded: false, // 页面加载状态
    }
  },
  
  // 页面加载生命周期
  onLoad(){
    // 400ms后显示页面内容
    setTimeout(() => {
      this.loaded = true
    }, 400)
  },
  
  computed: {
    // 验证邮箱格式
    isValidEmail() {
      return /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/.test(this.email)
    },
    
    // 计算密码强度
    passwordStrength() {
      if (!this.password) return 0
      let strength = 0
      if (this.password.length >= 8) strength += 1
      if (/[a-z]/.test(this.password)) strength += 1
      if (/[A-Z]/.test(this.password)) strength += 1
      if (/\d/.test(this.password)) strength += 1
      if (/[!@#$%^&*]/.test(this.password)) strength += 1
      return strength
    },
    
    // 密码强度CSS类
    passwordStrengthClass() {
      if (this.passwordStrength <= 2) return 'weak'
      if (this.passwordStrength <= 3) return 'medium'
      return 'strong'
    },
    
    // 密码强度条宽度
    passwordStrengthWidth() {
      return (this.passwordStrength / 5 * 100) + '%'
    },
    
    // 密码强度文本
    passwordStrengthText() {
      if (this.passwordStrength <= 2) return '弱'
      if (this.passwordStrength <= 3) return '中等'
      return '强'
    },
    
    // 密码是否匹配
    passwordsMatch() {
      return this.password && this.confirmPassword && this.password === this.confirmPassword
    },
    
    // 是否可以注册
    canRegister() {
      return this.isValidEmail && 
             this.verificationCode.length === 6 && 
             this.password.length >= 6 && 
             this.passwordsMatch && 
             this.agreedToTerms && 
             !this.isRegistering
    }
  },
  
  methods: {
    // 邮箱输入处理
    onEmailInput(e) {
      this.email = e.detail.value
    },
    
    // 输入框获取焦点
    focusField(field) {
      this.focusedField = field
    },
    
    // 输入框失去焦点
    blurField(field) {
      if (this.focusedField === field) {
        this.focusedField = ''
      }
    },
    
    // 切换密码可见性
    togglePassword() {
      this.showPassword = !this.showPassword
    },
    
    // 切换确认密码可见性
    toggleConfirmPassword() {
      this.showConfirmPassword = !this.showConfirmPassword
    },
    
    // 切换协议同意状态
    toggleAgreement() {
      this.agreedToTerms = !this.agreedToTerms
    },
    
    // 发送验证码
    async sendCode() {
      if (!this.isValidEmail || this.countdown > 0) return
      
      try {
        // 开始60秒倒计时
        this.countdown = 60
        const timer = setInterval(() => {
          this.countdown--
          if (this.countdown <= 0) {
            clearInterval(timer)
          }
        }, 1000)
        
        // 准备请求参数
        const params = new URLSearchParams()
        params.append('email', this.email)
        
        // 发送验证码请求
        const res = await request.post('/send-verification-code', params, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })
        
        if (res.data.status === 'success') {
          uni.showToast({
            title: '验证码已发送',
            icon: 'success'
          })
        } else {
          // 发送失败重置倒计时
          this.countdown = 0
          clearInterval(timer)
          
          uni.showToast({
            title: res.data.message || '验证码发送失败',
            icon: 'none'
          })
        }
        
      } catch (err) {
        // 网络异常重置倒计时
        this.countdown = 0
        
        console.error('发送验证码失败:', err)
        uni.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        })
      }
    },
    
    // 处理注册
    handleRegister() {
      if (!this.canRegister) return
      this.isRegistering = true
      
      // 准备注册参数
      const params = new URLSearchParams()
      params.append('email', this.email)
      params.append('code', this.verificationCode)
      params.append('password', this.password)
      
      // 发送注册请求
      request.post('/verify-code', params.toString(), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        }
      }).then(res => {
        this.isRegistering = false
        console.log(res)
        
        if (res.success) {
          uni.showToast({
            title: '注册成功',
            icon: 'success'
          })
          // 1秒后跳转到应用中心
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/AppCenter/AppCenter'
            })
          }, 1000)
        } else {
          uni.showToast({
            title: res.data.message || '注册失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        this.isRegistering = false
        console.error('注册失败:', err)
        uni.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        })
      })
    },
    
    // 跳转到登录页
    goLogin() {
      uni.navigateTo({
        url: '/pages/Login/Login'
      })
    },
    
    // 查看用户协议
    viewTerms() {
      uni.showModal({
        title: '用户协议',
        content: `欢迎使用我们的服务。在您注册成为用户之前，请仔细阅读本协议的所有内容。
本协议包括但不限于用户的权利、义务、限制条款、免责条款等内容。
如您不同意本协议的任意内容，请不要注册账户或使用我们的服务。`,
        showCancel: false
      })
    },
    
    // 查看隐私政策
    viewPrivacy() {
      uni.showModal({
        title: '隐私政策',
        content: `我们非常重视您的隐私和个人信息保护。我们会严格按照法律法规保护您在使用服务过程中提供的信息。
我们承诺不会将您的个人信息用于未经授权的用途，除非获得您的明确同意或法律要求。`,
        showCancel: false
      })
    }
  }
}
</script>
<style lang="scss">
.register-container {
  opacity: 0;
  transform: translateY(30rpx);
  transition: all 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  min-height: 100vh;
  background: linear-gradient(135deg, #ff6b6b 0%, #ffa500 50%, #ff69b4 100%);
  position: relative;
  overflow: hidden;
}

/* 显示页面时的动画效果 */
.register-container.show {
  opacity: 1;
  transform: translateY(0);
}

/* 顶部波浪装饰样式 */
.header-wave {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 200rpx;
  
  .wave-shape {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 0 0 60% 40%;
    transform: scale(1.1);
  }
}

/* 标题区域样式 */
.title-section {
  padding: 140rpx 40rpx 60rpx;
  text-align: center;
}

.title-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
  position: relative;
}

/* 脉冲动画圆点 */
.pulse-dot {
  width: 24rpx;
  height: 24rpx;
  background: white;
  border-radius: 50%;
  margin-right: 20rpx;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    width: 24rpx;
    height: 24rpx;
    border-radius: 50%;
    background: white;
    animation: pulse 1.5s infinite;
  }
}

/* 脉冲动画 */
@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  100% {
    transform: scale(2.5);
    opacity: 0;
  }
}

.main-title {
  color: white;
  font-size: 56rpx;
  font-weight: bold;
  text-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
}

.subtitle {
  color: rgba(255, 255, 255, 0.9);
  font-size: 28rpx;
}

/* 表单容器样式 */
.form-container {
  background: rgba(26, 26, 26, 0.95);
  margin: 0 30rpx;
  border-radius: 32rpx;
  padding: 50rpx 40rpx;
  backdrop-filter: blur(20rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
}

/* 输入组样式 */
.input-group {
  margin-bottom: 40rpx;
}

/* 浮动标签输入框容器 */
.floating-label-wrapper {
  position: relative;
  background: #333;
  border-radius: 20rpx;
  border: 2rpx solid rgba(105, 105, 105, 0.4);
  transition: all 0.3s ease;
  
  &:focus-within {
    border-color: #00bfff;
    background: #444;
    box-shadow: 0 0 0 6rpx rgba(0, 191, 255, 0.1);
  }
}

/* 输入框样式 */
.floating-input {
  width: 100%;
  padding: 40rpx 80rpx 20rpx 60rpx;
  background: transparent;
  color: white;
  font-size: 32rpx;
  border: none;
  outline: none;
}

/* 浮动标签样式 */
.floating-label {
  position: absolute;
  left: 60rpx;
  top: 30rpx;
  color: rgba(255, 255, 255, 0.5);
  font-size: 32rpx;
  transition: all 0.3s ease;
  pointer-events: none;
  
  &.focused {
    top: 12rpx;
    font-size: 24rpx;
    color: #00bfff;
    font-weight: 600;
  }
}

/* 输入框图标样式 */
.input-icon {
  position: absolute;
  left: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  
  .icon {
    font-size: 32rpx;
  }
}

/* 眼睛图标样式 */
.eye-icon {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
  
  .icon {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.6);
  }
}

/* 验证码容器样式 */
.verification-wrapper {
  display: flex;
  gap: 20rpx;
  align-items: flex-start;
}

.verification-input {
  flex: 1;
}

/* 验证码按钮样式 */
.code-btn {
  height: 80rpx;
  padding: 0 24rpx;
  background: linear-gradient(135deg, #00bfff, #0099cc);
  color: white;
  border: none;
  border-radius: 16rpx;
  font-size: 24rpx;
  font-weight: 500;
  transition: all 0.3s ease;
  white-space: nowrap;
  
  &.disabled {
    background: #555;
    color: #999;
  }
  
  &:not(.disabled):active {
    transform: scale(0.95);
  }
}

/* 密码强度指示器样式 */
.password-strength {
  margin-top: 16rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.strength-bar {
  flex: 1;
  height: 6rpx;
  background: #444;
  border-radius: 3rpx;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
  
  &.weak {
    background: #ff4757;
  }
  
  &.medium {
    background: #ffa502;
  }
  
  &.strong {
    background: #2ed573;
  }
}

.strength-text {
  font-size: 24rpx;
  font-weight: 500;
  
  &.weak {
    color: #ff4757;
  }
  
  &.medium {
    color: #ffa502;
  }
  
  &.strong {
    color: #2ed573;
  }
}

/* 密码匹配提示样式 */
.password-match {
  margin-top: 16rpx;
}

.match-text {
  font-size: 24rpx;
  font-weight: 500;
  
  &.match {
    color: #2ed573;
  }
  
  &.no-match {
    color: #ff4757;
  }
}

/* 用户协议区域样式 */
.agreement-section {
  margin-bottom: 50rpx;
}

.checkbox-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 16rpx;
}

.custom-checkbox {
  width: 36rpx;
  height: 36rpx;
  border: 2rpx solid #666;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  flex-shrink: 0;
  margin-top: 6rpx;
  
  &.checked {
    background: #00bfff;
    border-color: #00bfff;
  }
  
  .checkmark {
    color: white;
    font-size: 24rpx;
    font-weight: bold;
  }
}

.agreement-text {
  color: rgba(255, 255, 255, 0.7);
  font-size: 26rpx;
  line-height: 1.6;
}

.link-text {
  color: #00bfff;
  text-decoration: underline;
}

/* 注册按钮样式 */
.register-btn {
  width: 100%;
  height: 100rpx;
  background: linear-gradient(135deg, #00bfff 0%, #0099cc 100%);
  border: none;
  border-radius: 20rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 191, 255, 0.3);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  
  &.disabled {
    background: #555;
    box-shadow: none;
    
    .btn-text {
      color: #999;
    }
  }
  
  &:not(.disabled):active {
    transform: translateY(2rpx);
    box-shadow: 0 5rpx 15rpx rgba(0, 191, 255, 0.3);
  }
  
  .btn-text {
    color: white;
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .btn-loading {
    position: absolute;
    right: 30rpx;
    top: 50%;
    transform: translateY(-50%);
    
    .loading-text {
      font-size: 32rpx;
      animation: spin 1s linear infinite;
    }
  }
}

/* 加载动画 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 登录提示样式 */
.login-hint {
  text-align: center;
  
  .hint-text {
    color: rgba(255, 255, 255, 0.7);
    font-size: 28rpx;
  }
  
  .login-link {
    color: #00bfff;
    font-size: 28rpx;
    font-weight: 500;
    margin-left: 8rpx;
  }
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .form-container {
    margin: 0 20rpx;
    padding: 40rpx 30rpx;
  }
  
  .title-section {
    padding: 120rpx 30rpx 50rpx;
  }
}
</style>